package com.kotlin.book.adapter

import android.graphics.Typeface
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.RecyclerView
import com.kotlin.book.R
import com.kotlin.book.databinding.ItemClassLeftBinding
import com.kotlin.book.entry.Type

class ClassLeftItemAdapter(
    private var itemList: List<Type>,
    //回调
    private val callback: (Int) -> Unit
) : RecyclerView.Adapter<ClassLeftItemAdapter.ViewHolder>() {
    private var currentIndex = 0

    class ViewHolder(itemBinding: ItemClassLeftBinding) :
        RecyclerView.ViewHolder(itemBinding.root) {
        val bookClass = itemBinding.bookClass
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding =
            ItemClassLeftBinding.inflate(LayoutInflater.from(parent.context), parent, false)
        return ViewHolder(binding)
    }

    override fun getItemCount(): Int {
        return itemList.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val item = itemList[position]
        holder.bookClass.text = item.name

        if (currentIndex == position) {
            holder.bookClass.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16f)
            holder.bookClass.setTypeface(null, Typeface.BOLD)
            holder.bookClass.setTextColor(
                ContextCompat.getColor(
                    holder.itemView.context,
                    R.color.text_color_primary
                )
            )
            holder.bookClass.background =
                ContextCompat.getDrawable(holder.itemView.context, R.drawable.class_left_bg)
        } else {
            holder.bookClass.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14f)
            holder.bookClass.setTypeface(null, Typeface.NORMAL)
            holder.bookClass.setTextColor(
                ContextCompat.getColor(
                    holder.itemView.context,
                    R.color.text_color_secondary
                )
            )
            holder.bookClass.background = null
        }

        holder.itemView.setOnClickListener {
            currentIndex = holder.adapterPosition
            callback(currentIndex)
            notifyDataSetChanged() // 更新所有项的状态
        }
    }

    fun setData(data: MutableList<Type>) {
        itemList = data
        notifyDataSetChanged()
    }

    fun setCurrentIndex(index: Int) {
        currentIndex = index
        notifyDataSetChanged()
    }

}